package idiolect.helpers;

import javax.swing.*;

public abstract class AbstractHelper implements Runnable {
    private final ResponseAcceptor requestor;
    protected final int taskID;
    protected final String request;
    protected String response;


    public AbstractHelper(String request, ResponseAcceptor requestor, int taskID) {
        this.request = request;
        this.requestor = requestor;
        this.taskID = taskID;
    }

    public int getTaskID() {
        return taskID;
    }

    public void doRequest() {
        final Thread th = new Thread(this);
        th.start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    th.join();
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            requestor.setResponse(AbstractHelper.this, response);
                        }
                    });
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    public String getRequest() {
        return request;
    }

    public String getResponse() {
        return response;
    }

    public static AbstractHelper stub(final ResponseAcceptor requestor, String request, final String stubResponse, int taskID) {
        return new AbstractHelper(request, null, taskID) {

            public void doRequest() {
                requestor.setResponse(this, stubResponse);
            }


            public String getResponse() {
                return stubResponse;
            }

            public void run() {
                //do nothing
            }
        };
    }
}
